<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <el-card class="box-card">
      <div slot="header" style="display:flex;align-items: center;justify-content: space-between;">
        <span>商品管理</span>
        <div>
          <el-button @click="onClickAdd" size="small" icon="el-icon-plus" type="success">添加商品</el-button>
          <!-- <el-upload :show-file-list="false" style="display:inline-block" action="https://jsonplaceholder.typicode.com/posts/" :limit="1">
            <el-button size="small" icon="el-icon-upload" type="danger">批量导入商品</el-button>
          </el-upload>
          <el-link href="https://dcdn.it120.cc/2020/03/05/56338722-cd76-4691-9838-29f63740b90a.xlsx" type="warning">下载excel模版</el-link> -->
        </div>
      </div>
      <div style="marginTop:20px" class="filter-container">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable @keyup.enter.native="onClickSearch" />
          </el-form-item>
          <el-form-item label="商品Code">
            <el-input v-model="searchForm.productCode" placeholder="请输入商品Code" clearable @keyup.enter.native="onClickSearch" />
          </el-form-item>
          <el-form-item label="热门商品">
            <el-switch v-model="searchForm.isHot" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <!-- <el-form-item label="是否上架">
            <el-switch v-model="searchForm.active" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item> -->
          <el-form-item label="分类列表">
            <el-cascader v-model="searchForm.categoryCode" :options="categoryList" @change="onChangeCategory" clearable :props="{label: 'categoryName',value: 'categoryCode'}"></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="onClickSearch">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格主体 -->
    <el-card style="marginTop:20px">
      <div slot="header">
        <span>商品列表</span>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%" :cell-class-name="changeCellStyle">>
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="productCode" label="商品Code" min-width="150" />
          <el-table-column prop="price" label="原价" />
          <el-table-column prop="soldPrice" label="售价" />
          <el-table-column prop="stock" label="库存" />
          <el-table-column prop="soldStock" label="销量" />
          <!-- <el-table-column prop="categoryCode" label="所属目录">
            <template slot-scope="scope">
              <span>{{ allCategoryList[scope.row.categoryCode] }}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="pic" label="缩略图">
            <template slot-scope="scope">
              <img width="64" height="64" :src="scope.row.pic" alt="">
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.isHot" content="热门" placement="top">
                <i class="el-icon-s-flag icon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="操作" width="180px">
            <template slot-scope="scope">
              <el-button v-if="scope.row.isHot" type="text" @click="onClickSetHot(scope.row)">取消热门</el-button>
              <el-button v-else type="text" @click="onClickSetHot(scope.row)">设置热门</el-button>
              <el-button @click="onClickDelete(scope.row)" type="text" class="red">删除</el-button>
              <el-button @click="onClickEdit(scope.row)" type="text">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="prev, pager, next" @current-change="currentChange" :page-count="Math.ceil(this.pageInfo.total / this.pageInfo.pageSize)"></el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Category',
  data() {
    return {
      formLabelWidth: '120px',
      tableData: [],
      searchForm: {
        categoryCode: [], // 选中的分类
        productName: '', // 商品名称
        productCode: '', // 商品编码
        isHot: 0, // 是否热门0:否 1:是
        // active: 0, // 是否上架0:下架 1:上架
      },
      categoryList: [], // 分类列表
      allCategoryList: {}, // 所有分类 包括二级目录

      pageInfo: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 展示数量
        total: 1, // 总记录数
      },
    };
  },
  mounted() {
    this.getCategoryList();
    this.getProductList();
  },
  methods: {
    changeCellStyle({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 6) {
        return 'img-column';
      }
    },
    /**
     * 分类列表
     */
    onChangeCategory(row) {
      console.log('row', row);
      if (this.searchForm.categoryCode.length > 1) {
        this.searchForm.categoryCode = this.searchForm.categoryCode[
          this.searchForm.categoryCode.length - 1
        ];
      }
    },
    /**
     * 查询
     */
    onClickSearch() {
      this.pageInfo.pagesNo = 1;
      this.pageInfo.pageNum = 1;
      this.getProductList();
    },
    /**
     * 添加
     */
    onClickAdd() {
      this.$router.push({ path: '/market/goods/detail' });
    },
    /**
     * 编辑
     */
    onClickEdit({ productCode }) {
      this.$router.push({
        path: '/market/goods/detail',
        query: { code: productCode },
      });
    },
    async onClickSetHot(goods) {
      const message = goods.isHot
        ? '确定取消该商品为热门商品？'
        : '确定将该商品设置为热门商品';

      const confirm = await this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => {});

      confirm && this.updateProdcut(goods);
    },
    /**
     * 删除
     */
    async onClickDelete(goods) {
      const confirm = await this.$confirm(
        `此操作将永久删除该商品, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deleteProduct(goods);
    },

    /**
     * 分页
     */
    currentChange(pages) {
      this.pageInfo.pageNum = pages;
      this.getProductList();
    },

    async getCategoryList() {
      const response = await this.$api.getCategoryList();
      const { data } = response;
      this.categoryList = data;
    },

    async getProductList() {
      const params = {
        ...{},
        ...{
          pageNum: this.pageInfo.pageNum,
          pageSize: this.pageInfo.pageSize,
          needTotalCount: true,
        },
        ...this.searchForm,
      };
      if (!this.searchForm.isHot) {
        delete params.isHot;
      }
      const response = await this.$api.getProductList(params);
      if (response.success) {
        this.tableData = response.data;
        this.pageInfo.total = response.total;
      }
    },
    async deleteProduct(goods) {
      const response = await this.$api.deleteProduct({
        productId: goods.productId,
      });
      if (response.success) {
        this.$message.success('删除成功');
        this.getProductList();
      }
    },

    async updateProdcut(goods) {
      const response = await this.$api.updateProdcut({
        isHot: +!goods.isHot,
        productCode: goods.productCode,
      });
      if (response.success) {
        this.$message.success('设置成功');
        this.getProductList();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .table-wrapper {
    margin-top: 20px;
  }
  .pagination {
    padding-top: 20px;
    text-align: center;
  }
  .icon {
    color: red;
    font-size: 20px;
    cursor: pointer;
  }
}

::v-deep .img-column {
  .cell {
    text-overflow: unset;
  }
}
</style>
